from rest_framework.decorators import action
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.viewsets import ReadOnlyModelViewSet

from meiduo_admin.utils import PageNum
from orders.models import OrderInfo
from meiduo_admin.serializers.orders import OrdersSerializer


class OrderView(ReadOnlyModelViewSet):
    queryset = OrderInfo.objects.all()
    permission_classes = [IsAdminUser]
    pagination_class = PageNum
    serializer_class = OrdersSerializer

    # 重写get-queryset 方法
    def get_queryset(self):

        if self.request.query_params.get('keyword') == '':
            return OrderInfo.objects.all()
        elif self.request.query_params.get('keyword') is None:
            return OrderInfo.objects.all()
        else:
            return OrderInfo.objects.filter(order_id__contains=self.request.query_params.get('keyword'))

    @action(methods=['put'],detail=True)
    def status(self,request, pk):

        try:
            order = OrderInfo.objects.get(order_id=pk)
        except:
            return Response({'error':"订单编号错误"})

        # 获取订单状态并修改
        status = request.data.get('status')
        if status is None:
            return Response({"error": "缺少必传的参数"})
        # 保存数据
        order.status = status
        order.save()

        return Response({
            'order_id': pk,
            "status": status
        })
